import React, { Component } from 'react'
import { PickerView } from 'antd-mobile'
import FilterFooter from '../../../../components/FilterFooter/index.jsx'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as filterActionCreators from '../../../../store/actionCreators/filtersActionCreators'

class FilterPicker extends Component {
  state = {
    value: this.props.selectValue[this.props.openType],
    openType: this.props.openType
  }

  // 更改了选中的值
  onChange = value => {
    this.setState({
      value
    })
  }

  static getDerivedStateFromProps(props, state) {
    if (state.openType !== props.openType) {
      return {
        ...state,
        ...{
          value: props.selectValue[props.openType],
          openType: props.openType
        }
      }
    } else {
      return state
    }
  }

  render() {
    const {
      openType,
      area,
      price,
      rentType,
      subway,
      setOpenType,
      setSelectValue
    } = this.props

    let data = null
    switch (openType) {
      case 'area':
        data = [area, subway]
        break

      case 'mode':
        data = rentType
        break

      case 'price':
        data = price
        break

      default:
        break
    }

    return (
      <>
        {/* 选择器组件： */}
        <PickerView
          data={data}
          onChange={this.onChange}
          cols={openType === 'area' ? 3 : 1}
          value={this.state.value}
        />

        {/* 底部按钮 */}
        <FilterFooter
          onCancel={() => setOpenType('')}
          onSave={() => {
            setSelectValue({
              [openType]: this.state.value
            })
          }}
        />
      </>
    )
  }
}

export default connect(
  ({
    filters: {
      openType,
      filterData: { area, price, rentType, subway },
      selectValue
    }
  }) => {
    return { openType, area, price, rentType, subway, selectValue }
  },
  dispatch => bindActionCreators(filterActionCreators, dispatch)
)(FilterPicker)
